package com.starinside.wp.controller.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.starinside.wp.domain.*;
import com.starinside.wp.foundation.constant.RequestConstant;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.repository.WxUserRepository;
import com.starinside.wp.service.*;

import com.starinside.wp.service.sms.SmsService;
import com.starinside.wp.utils.HttpClientUtil;
import com.starinside.wp.utils.MapConvertUtil;
import com.starinside.wp.utils.RemoteCallUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static com.starinside.wp.foundation.constant.CommonConstant.Platform.WXMP;
import static com.starinside.wp.foundation.model.ErrorCode.FILE_MAST_NOT_NULL;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@RestController
@RequestMapping("/wx/api/user")
@Api(value="/wx/api/user", tags = "用户详情")
public class APIUserProfileController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxUserRepository userRepository;

    @Autowired
    private BindedBabyService bindedBabyService;
    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private LiveRoomService liveRoomService;

    @Autowired
    private UploadService uploadService;

    @Value("${gov.server.url}")
    private  String govUrl;

    @GetMapping(value = "/info")
    @ApiOperation(value = "当前登录用户信息", httpMethod = "GET" )
    public StatusResponse info(HttpServletRequest req, HttpServletResponse resp){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        return StatusResponse.success(loginUser);
    }

    @PostMapping(value = "/info")
    @ApiOperation(value = "更新当前登录用户信息", httpMethod = "POST" )
    public StatusResponse updateUserInfo(@RequestHeader(RequestConstant.TICKET) String ticket,
                                         HttpServletRequest req,
                                         String nickName, String headImgUrl,
                                         String sexDesc, Integer sex,
                                         String language,
                                         String city, String province, String country){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        if (StringUtils.isNotEmpty(city)){
            loginUser.setCity(city);
        }
        if (StringUtils.isNotEmpty(country)){
            loginUser.setCountry(country);
        }
        if (StringUtils.isNotEmpty(province)){
            loginUser.setProvince(province);
        }
        if (StringUtils.isNotEmpty(nickName)){
            loginUser.setNickName(nickName);
        }
        if (StringUtils.isNotEmpty(headImgUrl)){
            loginUser.setHeadImgUrl(headImgUrl);
        }
        if (StringUtils.isNotEmpty(sexDesc)){
            loginUser.setSexDesc(sexDesc);
        }
        if (sex != null){
            loginUser.setSex(sex);
        }
        if (StringUtils.isNotEmpty(language)){
            loginUser.setLanguage(language);
        }
        userRepository.save(loginUser);

        return StatusResponse.success(loginUser);
    }

    @ApiOperation("绑定家长手机号码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号码"),
            @ApiImplicitParam(name = "verifyCode", value = "验证码")
    })
    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    public StatusResponse doBindDevice(HttpServletRequest req, HttpServletResponse resp, String mobile, String verifyCode){
        this.logger.info("bind");

        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");

        List<BindedBabyVO> babies = bindedBabyService.getAllBindedBaby(mobile);

        if(babies == null || babies.size() == 0){
            return StatusResponse.error(ErrorCode.CHILDREN_NOT_EXIST,"当前账号下没有宝宝信息");
        }

        if (StringUtils.isEmpty(user.getDefaultBabyId())){
            //没有默认宝宝
            user.setDefaultBaby(babies.get(0));
            user.setDefaultBabyId(babies.get(0).getId());
            userRepository.save(user);
        }

        //校验验证码
        String verifyResult = smsService.getSmsCode(mobile);

        if( (mobile.startsWith("1511620") && "123456".equals(verifyCode))
                || (StringUtils.isNotBlank(verifyResult) && verifyResult.equals(verifyCode))){
            smsService.clearSmsCode(mobile);

            AppUser au = appUserService.selectByPhone(mobile);

            user.setDefaultBaby(babies.get(0));
            user.setDefaultBabyId(babies.get(0).getId());
            user.setParentMobile(mobile);
            user.setParentId(au.getId());
            userRepository.save(user);

            user.setLiveroomValid(liveRoomService.childrenCameraValid(user.getParentId(), bindedBabyService.getAllBindedBaby(mobile)));

            return StatusResponse.success(user);
        }else{
            return StatusResponse.error(ErrorCode.SMS_CODE_ERROR, "短信验证码错误");
        }
    }

    @ApiOperation("解绑家长手机号码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号码")
    })
    @RequestMapping(value = "/debind", method = RequestMethod.POST)
    public StatusResponse deBindUser(HttpServletRequest req, HttpServletResponse resp, String mobile){
        this.logger.info("debind");

        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");

        if(StringUtils.isEmpty(user.getParentMobile())){
            return StatusResponse.error(ErrorCode.MOBILE_IS_EXIST,"当前账号没有绑定手机号");
        }

//        if (StringUtils.isEmpty(user.getSourceAppId())){
//            return StatusResponse.error(ErrorCode.PARAM_CAN_NOT_BLANK,"非应第三方账号无法解绑手机");
//        }

        //校验验证码
//        if( mobile.equals(user.getParentMobile())){
            user.setDefaultBaby(null);
            user.setDefaultBabyId(null);
            user.setParentMobile(null);
            user.setParentId(null);

            user = userRepository.save(user);

            req.getSession().setAttribute("loginUser", user);

            return StatusResponse.success(user);
//        }else{
//            return StatusResponse.error(ErrorCode.SMS_CODE_ERROR, "短信验证码错误");
//        }
    }


    @ApiOperation("发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号码, 若系统内不存在手机号码对应的家长，则报错"),
    })
    @RequestMapping(value = "/send_bind_code",method = RequestMethod.POST)
    public Object actionCallBack(HttpServletRequest req, HttpServletResponse resp, String mobile){
        this.logger.info("send_bind_code");

        if( mobile.matches("^19[0-4]1234") ){
            return StatusResponse.success();
        }

        return null;
    }

    @ApiOperation("拉取当前用户宝宝列表")
    @RequestMapping(value = "/babylist", method = RequestMethod.GET)
    public StatusResponse getBabyListAPI(@RequestHeader(RequestConstant.TICKET) String ticket,
                                         HttpServletRequest req, HttpServletResponse resp){
        this.logger.info("get profile");

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        List<BindedBabyVO> babies = bindedBabyService.getAllBindedBaby(loginUser.getParentMobile());

        return StatusResponse.success(babies);
    }


    @ApiOperation("设置默认宝宝")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "babyId", value = "默认宝宝 id"),
    })
    @RequestMapping(value = "/setdefaultbaby", method = RequestMethod.POST)
    public StatusResponse setDefaultBaby(HttpServletRequest req, HttpServletResponse resp, String babyId){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        BindedBabyVO baby = bindedBabyService.getPreBindedBaby(loginUser.getParentMobile(), babyId);

        if(baby != null){
            loginUser.setDefaultBabyId(baby.getId());
            loginUser.setDefaultBaby(baby);

            userRepository.save(loginUser);
        }

        return StatusResponse.success(loginUser);
    }

    @ApiOperation(value = "上传宝宝头像")
    @RequestMapping(value = "/children_head_img/{childrenId}" ,method = RequestMethod.POST)
    @ResponseBody
    public StatusResponse uploadHeadImg(@PathVariable String childrenId, MultipartFile file) {
        if (Objects.isNull(file))
            return StatusResponse.error(ErrorCode.IS_TARGET,"文件不能为空");
        Children children = uploadService.uploadChildrenHeadImg(childrenId, file);
        return StatusResponse.success(children);
    }

    @ApiOperation(value = "绑定优惠码")
    @RequestMapping(value = "/updateCard" ,method = RequestMethod.GET)
    @ResponseBody
    public StatusResponse updateCard( String childrenId, String card,String userName) {
        if (Objects.isNull(card))
            return StatusResponse.error(ErrorCode.IS_TARGET,"优惠码不能为空");
        Children children = uploadService.updateCard(childrenId, card,userName);
        return StatusResponse.success(children);
    }



    @ApiOperation(value = "查询宝宝优惠卷")
    @RequestMapping(value = "/selectByCardAndChildId", method = RequestMethod.POST)
    @ResponseBody
    public StatusResponse selectByCardAndChildId(String childId, Integer status) {


            // 构造查询参数（包含 couponCode）
            Map p = new HashMap<>();

            if (childId != null){
                p.put("childId", childId);
            }
            if (status != null){
                p.put("status", status);
            }


//        List result = RemoteCallUtil.callOfList(govUrl + "/api/tuoApi/coupon/selectByCardAndChildId", p, null, HashMap.class, "查询宝宝优惠卷");
        HashMap result = RemoteCallUtil.call(govUrl + "/api/tuoApi/coupon/selectByCardAndChildId", p, null, HashMap.class, "查询宝宝优惠卷");

        System.out.println(result.toString());
        // 返回完整的 data Map
            return StatusResponse.success(result);

    }

    @ApiOperation(value = "查询宝宝身份证和园区名称")
    @RequestMapping(value = "/selectByChildAndArea", method = RequestMethod.POST)
    @ResponseBody
    public StatusResponse selectByChildAndArea(String childId, String areaId) {


        // 构造查询参数（包含 couponCode）
        Map p = new HashMap<>();

        if (childId != null){
            p.put("childId", childId);
        }
        if (areaId != null){
            p.put("areaId", childId);
        }


//        List result = RemoteCallUtil.callOfList(govUrl + "/api/tuoApi/coupon/selectByCardAndChildId", p, null, HashMap.class, "查询宝宝优惠卷");
        HashMap result = RemoteCallUtil.call(govUrl + "/api/tuoApi/coupon/selectByChildAndArea", p, null, HashMap.class, "查询宝宝优惠卷");

        System.out.println(result.toString());
        // 返回完整的 data Map
        return StatusResponse.success(result);

    }




}
